# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _


class SaleOrder(models.Model):
    _inherit = 'sale.order'

    mrp_production_count = fields.Integer(
        "Count of MO generated",
        compute='_compute_mrp_production_ids',
        groups='mrp.group_mrp_user')
    mrp_production_ids = fields.Many2many(
        'mrp.production',
        compute='_compute_mrp_production_ids',
        string='Manufacturing orders associated with this sales order.',
        groups='mrp.group_mrp_user')

    @api.depends('stock_reference_ids.production_ids')
    def _compute_mrp_production_ids(self):
        for sale in self:
            # We want only manufacturing orders of first level
            mos = sale.stock_reference_ids.production_ids
            sale.mrp_production_ids = mos.filtered(lambda mo: not mo.production_group_id.parent_ids and mo.state != 'cancel')
            sale.mrp_production_count = len(sale.mrp_production_ids)

    def action_view_mrp_production(self):
        self.ensure_one()
        action = {
            'res_model': 'mrp.production',
            'type': 'ir.actions.act_window',
        }
        if len(self.mrp_production_ids) == 1:
            action.update({
                'view_mode': 'form',
                'res_id': self.mrp_production_ids.id,
            })
        else:
            action.update({
                'name': _("Manufacturing Orders Generated by %s", self.name),
                'domain': [('id', 'in', self.mrp_production_ids.ids)],
                'view_mode': 'list,form',
            })
        return action
